import React from "react";
import { message } from "antd";
import custom_map_config from '@utils/custom_map_config';

import { findAreaSubjectSum, findSubjectDetailByCondition } from "@apis/markAreaApi";
import { drawGuardLine } from "./config";
const pointList = [
  {
    longitude: 118.87714106650792,
    latitude: 26.12146366400454,
    weatherType: 'BY',
    weatherName: '暴雨',
    radius: 200, //影响半径
    fillColor: '#ff98002e'
  },
  {
    longitude: 113.8015577312885,
    latitude: 22.85201621863414,
    weatherType: 'TF',
    weatherName: '台风',
    radius: 400,
    fillColor: '#eac2193b' //颜色类型（不同天气不同颜色）
  },

]
const mapUtils = (setSpinning, drawerRef, setAddress = Function, setAreaList = Function) => {
  let superiorAreaName = '' // 保存上一个的区域AreaName
  let currentaddress = '' // 当前地址
  let isSearchSubmit = false; // 是否点击了查询
  let banZoomend = false; // 禁用地图缩放

  let map = null
  let geoc = null
  let bd = null

  // 初始化地图
  const initMap = () => {
    map = new BMapGL.Map("container"); // 创建Map实例
    React.Map = map
    map.centerAndZoom(new BMapGL.Point(115.60920134722626, 24.717743757939967), 6);// 初始化地图,设置中心点坐标和地图级别
    map.setMapStyleV2({
      styleJson: custom_map_config
    });
    map.enableScrollWheelZoom(true); //启用地图滚轮放大缩小
    map.disableDoubleClickZoom(); //	取消地图双击缩放
    map.setMinZoom(5);
    geoc = new BMapGL.Geocoder(); // 用于获取用户的地址解析
    bd = new BMapGL.Boundary(); // 创建一个行政区域的边界


    mapEvent()
  }
  const setMapCenter = (item) => {
    const { longitude, latitude } = item;
    if (!longitude || !latitude) {
      message.error("非常抱歉，该地址的经纬度有误");
    }
    React.Map.setCenter(new BMapGL.Point(longitude, latitude));
  };
  const mapEvent = () => {
    // 添加监听缩放事件
    map.addEventListener("dragend", (e) => {
      const zoom = map.getZoom();
      console.log("监听缩放事件：", zoom)
      if (zoom >= 8) {
        setLastAreaName();
      }
    });
    map.addEventListener("zoomend", (e) => {
      // 点击查询、禁用缩放状态直接返回
      if (isSearchSubmit || banZoomend) {
        isSearchSubmit = false
        banZoomend = false
        return
      };
      setLastAreaName();

    });
  }

  // 点击文本标记放大地图
  const setMapZoom = (BoundaryName) => {
    map.clearOverlays();

    const zoom = map.getZoom();
    geoc.getPoint(BoundaryName, (point) => {
      if (zoom < 8) {
        map.centerAndZoom(point, 9);
        return;
      }
      if (zoom < 11) {
        map.centerAndZoom(point, 12);
        return;
      }
      if (zoom < 13) {
        map.centerAndZoom(point, 14);
        return;
      }
    }, '中国');
  }

  // 处理 superiorAreaName
  const setLastAreaName = () => {
    const zoom = map.getZoom();
    const point = map.getCenter();
    geoc.getLocation(point, function (rs) {
      const addComp = rs.addressComponents;
      const province = addComp.province; //获取省份
      const city = addComp.city; //获取城市
      const district = addComp.district; //区
      if (zoom < 8) {
        superiorAreaName = "中国";
      } else if (zoom < 11) {
        superiorAreaName = province;
      } else if (zoom < 13) {
        superiorAreaName = province + city;
      }
      setLabelOrMarker();
    });
  }

  // 解析地址信息，分别设置省市区标记
  const setLabelOrMarker = () => {
    const center = map.getCenter();
    const zoom = map.getZoom();
    geoc.getLocation(center, function (rs) {
      const addComp = rs.addressComponents;
      const province = addComp.province; //获取省份
      const city = addComp.city; //获取城市
      const district = addComp.district; //区
      let address = "中国";

      const params = {
        provinceName: province,
        cityName: city,
        countyName: district,
        provinceCode: "",
        cityCode: "",
        countyCode: "",
        untiCode: "",
        riskCode: "",
        insured: "",
        policyNo: "",
      };
      if (zoom < 8) {
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        currentaddress = address
        getFindAreaSubjectSum({});

      } else if (zoom < 11) {
        address = province;
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        currentaddress = address
        getFindAreaSubjectSum({ areaName: province });

        // 东莞市，中山市没有维护到具体的区县，直接查详情
        if (city === '东莞市' || city === '中山市') {
          address = province + city
          if (currentaddress === address) return // 相同区域直接返回，不再发起请求
          currentaddress = address
          getMarkerPolicyDetails(params);
        }
      } else if (zoom < 13) {
        address = province + city;
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        currentaddress = address
        getFindAreaSubjectSum({ areaName: city });
      } else {
        address = province + city + district;
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        currentaddress = address;

        getMarkerPolicyDetails(params);
      }
      console.log("画标记点");
      // 设置灾害图标
      pointList.forEach(item => {
        setRiskMarker(item)
      })
      // 画警戒线
      drawGuardLine(map);
      console.log("address", address);
      setAddress(address);
    });

  }

  // 根据标记点获取详情
  const getMarkerPolicyDetails = async (params) => {
    const { data, error } = await findSubjectDetailByCondition(params);
    setSpinning(false);
    if (error) return
    // console.log('获取标记点的清单详情==>',data);
    setAreaList(data);
    setAddress(data);
    if (!data.length) {
      setSpinning(false);
      message.info('地图中心区域未查询到相关数据');
      return
    }

    if (data.some(item => item.hasGeoCircle)) {
      message.info('右键圆圈可查看整车仓储累计风险信息', 8);
    }

    data.forEach((item, i) => {
      if (i === 0) {
        if (isSearchSubmit) {
          map.centerAndZoom(new BMapGL.Point(item.longitude, item.latitude), 14)
        } else {
          banZoomend = true
          // map.setCenter(new BMapGL.Point(item.longitude, item.latitude))
        }

      }
      addMapMarker(item);
    });

  }
  // 根据经纬度添加详情文本标记
  const addMapMarker = (item,) => {
    const { longitude, latitude, policyHolder, hasGeoCircle, geoGroupAlertDto } = item;
    // 经纬度为空 直接返回
    if (!longitude || !latitude) return;

    const Point = new BMapGL.Point(longitude, latitude) // 指定文本标注所在的地理位置
    const opts = {
      position: Point,
    };
    const content = `
      <div class="text-label">
        ${policyHolder} | ${item.list.length} 条
        <i></i>
      </div>
    `;

    // 创建文本标注对象
    const label = new BMapGL.Label(content, opts);
    label.setStyle({
      borderRradius: "50%",
      backgroundColor: "transparent",
      border: "none",
    });
    map.addOverlay(label);

    const X = label.domElement.clientWidth / 2;
    const Y = label.domElement.clientHeight + 6;
    label.setOffset(new BMapGL.Size(-X, -Y));

    label.addEventListener("click", function (e) {
      drawerRef.current.showDrawer?.(item)
    });

    if (!hasGeoCircle) return

    const circleColor = color16()
    const circleOpts = {
      strokeColor: circleColor,
      strokeWeight: 3,
      fillColor: '',
      fillOpacity: 0.2

    }

    const Circle = new BMapGL.Circle(Point, geoGroupAlertDto?.radiusLength || 2000, circleOpts)
    map.addOverlay(Circle)

    const infoWindowContent = `
      <div>
        <label>地址：</label>
        <span style="color: #999">${geoGroupAlertDto.address}</span>
      </div>
      <div>
        <label>圈内地址数量：</label>
        <span class='count'>${geoGroupAlertDto.addressCount}</span>
      </div>
      <div>
        <label>圈内整车仓储累计保险价值(我司)：</label>
        <span class='money'>${geoGroupAlertDto.alertTotalPolicyAmount}</span>
      </div>
      <div style="margin-bottom: 10px">
        <label>整车仓储最大保险价值(我司)：</label>
        <span class='money'>${geoGroupAlertDto.cfgAlertPolicyAmount}</span>
      </div>
      
    `
    const infoWindow = new BMapGL.InfoWindow(infoWindowContent)
    infoWindow.setTitle('整车仓储累计风险')
    infoWindow.setWidth(333)

    Circle.addEventListener("rightclick", function (e) {
      map.openInfoWindow(infoWindow, Point); //开启信息窗口 
      infoWindow.redraw();
    });
    Circle.addEventListener("mouseover", function () {
      Circle.setFillColor(circleColor)
    });
    Circle.addEventListener("mouseout", function () {
      Circle.setFillColor('')
    });

  }
  // 根据经纬度添加文本标记
  const addMapLabel = (data) => {
    const { areaName, count, longitude, latitude } = data;

    // 经纬度为空 直接返回
    if (!longitude || !latitude) return;

    const point = new BMapGL.Point(longitude, latitude);
    const opts = {
      position: point, // 指定文本标注所在的地理位置
      offset: new BMapGL.Size(-42, -42), // 设置文本偏移量
    };

    const content = `
      <div class="text-box">
        <div class="text-box-titel">${areaName}</div>
        <div class="text-box-count">${count}</div>
      </div>
    `;

    // 创建文本标注对象
    const label = new BMapGL.Label(content, opts);
    label.setStyle({
      borderRradius: "50%",
      overflow: "hidden",
      backgroundColor: "transparent",
      borderColor: "transparent",
    });
    map.addOverlay(label);

    // 添加行政区域覆盖物
    const BoundaryName = map.getZoom() < 8 ? areaName : superiorAreaName + areaName; // 拼接地址，防止市、区同名的情况 如白云区
    let Polygon = null;
    bd.get(BoundaryName, function (rs) {
      if (!rs.boundaries.length) return
      Polygon = new BMapGL.Polygon(rs.boundaries, {
        strokeWeight: 2,
        strokeColor: "#3072f6",
        fillColor: "#3072f6",
        fillOpacity: 0.2,
      });

    });

    const textBox = label.domElement?.firstElementChild;
    if (!textBox) return

    textBox.onmouseenter = function (e) {
      if (!Polygon) return
      map.addOverlay(Polygon); //添加覆盖物
    };

    textBox.onmouseleave = function (e) {
      map.removeOverlay(Polygon); //删除覆盖物
    };

    textBox.onclick = function (e) {
      setMapZoom(BoundaryName, point);
    };

  }




  // 设置灾害图标
  function setRiskMarker(data) {
    const { longitude, latitude, weatherType, radius, fillColor } = data;

    // 经纬度为空 直接返回
    if (!longitude || !latitude) return;

    const point = new BMapGL.Point(longitude, latitude);

    const opts = {
      position: point, // 指定文本标注所在的地理位置
      offset: new BMapGL.Size(-23, -23), // 设置文本偏移量
    };



    const IconElement = `<div  class='weatherIcon ${weatherType}'></div>`
    // 创建文本标注对象
    const label = new BMapGL.Label(IconElement, opts);

    map.addOverlay(label);

    setPolygon({ longitude, latitude, radius, fillColor })


  }

  // 去设置圈圈    // 设置灾害的时候也设置范围圈
  function setPolygon({ longitude, latitude, radius, fillColor }) {
    var circle = new BMapGL.Circle(
      new BMapGL.Point(longitude, latitude),
      radius * 1000,
      {
        strokeColor: "#00ffff8a",
        fillColor: fillColor,
        strokeWeight: 1,
        strokeOpacity: 0.1
      }); //创建圆
    map.addOverlay(circle);
  }

  // 获取省市区汇总数据
  const getFindAreaSubjectSum = async (params) => {
    map.clearOverlays();
    setSpinning(true);
    const { data, error } = await findAreaSubjectSum(params);
    setAreaList(data);
    setSpinning(false)
    if (error) return;
    // console.log("获取省市区汇总数据==>", data);
    if (!data.length) {
      // setSpinning(false);
      message.info("地图中心区域未查询到相关数据");
      return;
    }
    data.forEach((item) => {
      addMapLabel(item);
    });

    setAreaList(data);
  }






  return {
    initMap,
    setLastAreaName,
    setMapCenter

  }
}

export default mapUtils